﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Moving03.Classes;

namespace Moving03
{
    public partial class WebForm8 : BasePage
    {
        DataClasses1DataContext context = new DataClasses1DataContext();
        int id_ttvc = 25;
        public static Guid lay_IDUser()
        {
            Guid userID = (Guid)Membership.GetUser().ProviderUserKey;
            return userID;
        }
        public void GanThongTinNoiDi()
        {

            var query = from nd in context.aspnet_Users
                        where nd.UserId == lay_IDUser()
                        select nd;

            foreach (var i in query)
            {
                Label1.Text = i.TenCongTy;
                Label2.Text = i.HoTen;
                var query1 = from datnuoc in context.DanhSachQuocGias
                             where datnuoc.Id_MaQGia == i.QuocGia
                             select datnuoc;
                foreach (var j in query1)
                    Label3.Text = j.TenQuocGia;

                Label4.Text = i.DiaChi1;
                Label5.Text = i.ThanhPho;
                Label6.Text = i.MaBuuDien.ToString();
                Label7.Text = i.DienThoai;
                Label8.Text = i.Email;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (Request.QueryString["idttvc"] != null)
                {
                    id_ttvc = int.Parse(Request.QueryString["idttvc"]);
                    ThongTinVanChuyen ttvc = context.ThongTinVanChuyens.Single(i => i.Id_TTVC == id_ttvc);
                    if (ttvc.TinhTrang != 1)
                    {
                        Response.Redirect("Default.aspx");
                    }
                    if (User.Identity.IsAuthenticated == false)
                    {
                        Response.Redirect("Login.aspx");
                    }
                    GanThongTinNoiDi();
                    
                    NoiDen noiDen = context.NoiDens.Single(i => i.Id_NoiDen == ttvc.IdNoiden);
                    NoiDi noiDi = context.NoiDis.Single(i => i.Id_Noidi == ttvc.IdNoiDi);
                    LoHang loHang = context.LoHangs.Single(i => i.Id_LoHang == ttvc.Id_LoHang);
                    MatHang matHang = null;
                    if (loHang.Giong_nhau == 1)
                        matHang = context.MatHangs.Single(i => i.Id_LoHang == ttvc.Id_LoHang);

                    if (ttvc != null)
                    {
                        // danh sach goi hang
                        ddlloaigoi.DataSource = context.PhuongThucGoiHangs;
                        ddlloaigoi.DataTextField = "LoaiPhat";
                        ddlloaigoi.DataValueField = "Id_GoiHang";
                        ddlloaigoi.DataBind();
                        // danh sach phương thức thanh toán
                        ddlphuongthucthanhtoan.DataSource = context.PhuongThucThanhToans;
                        ddlphuongthucthanhtoan.DataTextField = "TenThanhToan";
                        ddlphuongthucthanhtoan.DataValueField = "Id_ThanhToan";
                        ddlphuongthucthanhtoan.DataBind();
                        // danh sach các quốc gia
                        ddlQuocGia.DataSource = context.DanhSachQuocGias;
                        ddlQuocGia.DataTextField = "TenQuocGia";
                        ddlQuocGia.DataValueField = "Id_MaQGia";
                        ddlQuocGia.SelectedIndex = 1;
                        ddlQuocGia.DataBind();


                        aspnet_User user = context.aspnet_Users.Single(i => i.UserId == ttvc.Id_User);
                        Label1.Text = user.TenCongTy;
                        Label2.Text = user.HoTen;
                        DanhSachQuocGia getQG = context.DanhSachQuocGias.Single(i => i.Id_MaQGia == noiDi.Id_Quocgia);
                        Label3.Text = getQG.TenQuocGia;
                        Label4.Text = user.DiaChi1;
                        Label5.Text = noiDen.Thanhpho;
                        Label6.Text = noiDen.Mabuudien.ToString();
                        Label7.Text = noiDen.Dienthoai.ToString();
                        Label8.Text = noiDen.Email.ToString();

                        txtCongTy.Text = ttvc.TenDoanhNghiep;
                        txtTen.Text = ttvc.TenLienLac;
                        // danh sach các quốc gia
                        ddlQuocGia.DataSource = context.DanhSachQuocGias;

                        ddlQuocGia.DataTextField = "TenQuocGia";
                        ddlQuocGia.DataValueField = "Id_MaQGia";
                        ddlQuocGia.SelectedValue = noiDen.Id_Quocgia.ToString();
                        ddlQuocGia.DataBind();
                        txtDiaChi1.Text = noiDen.Diachi1;
                        txtDiaChi2.Text = noiDen.Diachi2;
                        txtThanhPho.Text = noiDen.Thanhpho;
                        txtMaBuuDien.Text = noiDen.Mabuudien.ToString();
                        txtDienThoai.Text = noiDen.Dienthoai.ToString();
                        txtEmail.Text = noiDen.Email;
                        if (noiDen.Nharieng == 1)
                        {
                            cbNhaRieng.Checked = true;
                        }

                        txtTenLienLacSuCo.Text = ttvc.TenNeuSuCo;
                        txtDiaChiTrahangve.Text = ttvc.DiaChiGoiNeuSuCo;
                        txtTenLoHang.Text = loHang.Ten_lo_hang;

                        if (!IsPostBack)
                        {
                            for (int i = 1; i <= 20; i++)
                            {
                                if (i == loHang.So_goi)
                                {
                                    ddlsogoi.Items.Add(i.ToString());
                                    ddlsogoi.SelectedValue = i.ToString();
                                }
                                else
                                {
                                    ddlsogoi.Items.Add(i.ToString());
                                }

                            }
                        }
                        if (loHang.Giong_nhau == 1)
                        {
                            ddlgiongnhau.SelectedValue = "1";
                        }
                        else
                        {
                            ddlgiongnhau.SelectedValue = "0";
                            txtTenMatHang.Enabled = false;
                            txtTrongLuong1Goi.Enabled = false;
                            RequiredFieldValidator6.Enabled = false;
                            RequiredFieldValidator9.Enabled = false;
                            //for(int i = 0; i < 
                        }
                        ddlgiongnhau.DataBind();
                        if (matHang != null)
                        {
                            txtTenMatHang.Text = matHang.TenMatHang.ToString();
                            txtTrongLuong1Goi.Text = matHang.TrongLuong.ToString();
                        }

                        txtTongKhoiLuong.Text = loHang.TongTrong_luong.ToString();
                        txtGiaTriUocLuong.Text = loHang.Gia_tri.ToString();

                        // danh sach goi hang
                        ddlloaigoi.DataSource = context.PhuongThucGoiHangs;
                        ddlloaigoi.DataTextField = "LoaiPhat";
                        ddlloaigoi.DataValueField = "Id_GoiHang";
                        ddlloaigoi.SelectedValue = ttvc.Id_PhuongThucGoiHang.ToString();
                        ddlloaigoi.DataBind();

                        txtBimat1.Text = ttvc.ThongTinBiMat1;
                        txtBiMat2.Text = ttvc.ThongTinBiMat2;
                        if (ttvc.NhanEmail == 1)
                        {
                            cbEmail.Checked = true;
                        }

                        if (ttvc.DungKiGoi == 1)
                        {
                            cbKiGoi.Checked = true;
                        }

                        if (ttvc.TacDongKhiHau == 1)
                        {
                            cbTacDong.Checked = true;
                        }

                        ddlphuongthucthanhtoan.DataSource = context.PhuongThucThanhToans;
                        ddlphuongthucthanhtoan.DataTextField = "TenThanhToan";
                        ddlphuongthucthanhtoan.DataValueField = "Id_ThanhToan";
                        ddlphuongthucthanhtoan.SelectedValue = ttvc.Id_PhuongThucThanhToan.ToString();
                        ddlphuongthucthanhtoan.DataBind();
                    }
                }
            }
        }

        public int updateNoiDi()
        {
            NoiDi ndi = new NoiDi();
            var query = from nd in context.aspnet_Users
                        where nd.UserId == lay_IDUser()
                        select nd;

            foreach (var i in query)
            {
                ndi.NguoiGoi = i.HoTen;
                ndi.Id_Quocgia = i.QuocGia;
                ndi.Diachi = i.DiaChi1;
                ndi.Thanhpho = i.ThanhPho;
                ndi.Mabuudien = i.MaBuuDien;
                ndi.Email = i.Email;
                ndi.Dienthoai = i.DienThoai;

            }
            //context.NoiDis.(ndi);
            context.SubmitChanges();
            return ndi.Id_Noidi;

        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            id_ttvc = int.Parse(Request.QueryString["idttvc"]);
            ThongTinVanChuyen ttvc = context.ThongTinVanChuyens.Single(i => i.Id_TTVC == id_ttvc);
            LoHang lh = context.LoHangs.Single(i => i.Id_LoHang == ttvc.Id_LoHang);
            string soGoiBanDau = lh.So_goi.ToString();
            string edit = null;
            if (lh.Giong_nhau == 1) // Ban đầu lô hàng có các mặt hàng đều giống nhau
            {
                if (ddlgiongnhau.SelectedValue.ToString() == "1") // Tiếp tục Update các lô hàng giống nhau.
                {
                    updateLoHang((int)ttvc.Id_LoHang);
                    updateNoiDen((int)ttvc.IdNoiden);
                    updateTTVC();
                    int id_ddcn = updateDiaDiemCapNhat(id_ttvc);
                    xoaDuongDiCu(id_ddcn);
                    updateDuongDiChoLoHang(id_ttvc, id_ddcn);
                }
                else // Update từ giống nhau thành khác nhau
                {
                    edit = "1";
                   
                    updateLoHang((int)ttvc.Id_LoHang);
                    updateNoiDen((int)ttvc.IdNoiden);
                    updateTTVC();
                    int id_ddcn = updateDiaDiemCapNhat(id_ttvc);
                    xoaDuongDiCu(id_ddcn);
                    updateDuongDiChoLoHang(id_ttvc, id_ddcn);
                    // Xoá mặt hàng cũ giống nhau
                    MatHang mh = context.MatHangs.Single(i => i.Id_LoHang == (int)ttvc.Id_LoHang);
                    context.MatHangs.DeleteOnSubmit(mh);
                    context.SubmitChanges();
                    //////////////
                    Response.Redirect("ThongTinLoHang.aspx?edit=" + edit + "&idlh=" + ttvc.Id_LoHang + "&smh=" + ddlsogoi.SelectedValue.ToString() + "&idttvc=" + id_ttvc);
                }
            }
            else // Ban đầu lô hàng có các mặt hàng đều khác nhau
            {
                if (ddlgiongnhau.SelectedValue.ToString() == "1") // Update lô hàng thành giống nhau
                {
                    //Xoá các mặt hàng khác nhau
                    IEnumerable<MatHang> matHang = context.MatHangs.Where(i => i.Id_LoHang == ttvc.Id_LoHang);
                    context.MatHangs.DeleteAllOnSubmit(matHang);
                    context.SubmitChanges();
                    //
                    updateLoHang((int)ttvc.Id_LoHang);
                    updateNoiDen((int)ttvc.IdNoiden);
                    updateTTVC();
                    int id_ddcn = updateDiaDiemCapNhat(id_ttvc);
                    xoaDuongDiCu(id_ddcn);
                    updateDuongDiChoLoHang(id_ttvc, id_ddcn);
                    
                }
                else // Update khác nhau vẫn là khác nhau
                {

                    if (soGoiBanDau != ddlsogoi.SelectedValue)
                    {
                        edit = "1";
                        IEnumerable<MatHang> matHang = context.MatHangs.Where(i => i.Id_LoHang == ttvc.Id_LoHang);
                        context.MatHangs.DeleteAllOnSubmit(matHang);
                        context.SubmitChanges();
                    }
                    else
                        edit = "2";
                    updateLoHang((int)ttvc.Id_LoHang);
                    updateNoiDen((int)ttvc.IdNoiden);
                    updateTTVC();
                    int id_ddcn = updateDiaDiemCapNhat(id_ttvc);
                    xoaDuongDiCu(id_ddcn);
                    updateDuongDiChoLoHang(id_ttvc, id_ddcn);
                    Response.Redirect("ThongTinLoHang.aspx?edit=" + edit + "&idlh=" + ttvc.Id_LoHang + "&smh=" + ddlsogoi.SelectedValue.ToString() + "&idttvc=" + id_ttvc);
                }
            }
            
        }
        public void xoaDuongDiCu(int id_ddcn)
        {
            IEnumerable<DuongDi> duongdi = context.DuongDis.Where(b => b.Id_DDCapNhat == id_ddcn);
            context.DuongDis.DeleteAllOnSubmit(duongdi);
            context.SubmitChanges();
        }
        public void updateDuongDiChoLoHang(int id_TTVC, int id_ddcn)
        {
            int id_noidi = 0;
            int id_noiden = 0;
            var query = from ttvc in context.ThongTinVanChuyens
                        join noidi in context.NoiDis on ttvc.IdNoiDi equals noidi.Id_Noidi
                        join noiden in context.NoiDens on ttvc.IdNoiden equals noiden.Id_NoiDen
                        where ttvc.Id_TTVC == id_TTVC
                        select new { id_noidi = noidi.Id_Quocgia, id_noiden = noiden.Id_Quocgia };


            foreach (var thongtin in query)
            {
                id_noidi = (int)thongtin.id_noidi;
                id_noiden = (int)thongtin.id_noiden;
            }

            var query1 = from cpddnn in context.ChiPhiDiaDiemNuocNgoais
                         join ddtg1t in context.DiaDiemTrungGian1Tuyens on cpddnn.Id_CPDDNNgoai equals ddtg1t.Id_CPDDNNgoai
                         join dd in context.DiaDiemTrungGians on ddtg1t.Id_TG equals dd.Id_DDTrungGian
                         where cpddnn.Id_QuocGia1 == id_noidi && cpddnn.Id_QuocGia2 == id_noiden
                         select dd;

            foreach (var dd in query1)
            {
                DuongDi duongdi = new DuongDi();
                duongdi.DaToiChua = 0;
                duongdi.Id_DDTGian = dd.Id_DDTrungGian;
                duongdi.Id_DDCapNhat = id_ddcn;
                context.DuongDis.InsertOnSubmit(duongdi);
                context.SubmitChanges();

            }

        }

        private int updateDiaDiemCapNhat(int id_TTVC)
        {
            DiaDiemCapNhat ddcn = context.DiaDiemCapNhats.Single(i => i.Id_ThongTinVanChuyen == id_ttvc);
            ddcn.Id_ThongTinVanChuyen = id_TTVC;
            //context.DiaDiemCapNhats.InsertOnSubmit(ddcn);
            context.SubmitChanges();
            int id_diadiemcapnhat = ddcn.Id_DDCapNHat;
            return id_diadiemcapnhat;
        }

        private int updateTTVC()
        {
            // insert thông tin vân chuyển
            ThongTinVanChuyen ttvc = context.ThongTinVanChuyens.Single(i => i.Id_TTVC == id_ttvc);

            ttvc.Id_PhuongThucThanhToan = int.Parse(ddlphuongthucthanhtoan.SelectedValue.ToString());
            ttvc.Id_PhuongThucGoiHang = int.Parse(ddlloaigoi.SelectedValue.ToString());
            ttvc.ThongTinBiMat1 = txtBimat1.Text;
            ttvc.ThongTinBiMat2 = txtBiMat2.Text;
            ttvc.TenDoanhNghiep = txtCongTy.Text;
            ttvc.TenLienLac = txtTen.Text;
            ttvc.TenNeuSuCo = txtTenLienLacSuCo.Text;
            ttvc.DiaChiGoiNeuSuCo = txtDiaChiTrahangve.Text;
            if (cbKiGoi.Checked == true)
                ttvc.DungKiGoi = 1;
            else
                ttvc.DungKiGoi = 0;

            if (cbEmail.Checked == true)
                ttvc.NhanEmail = 1;
            else
                ttvc.NhanEmail = 0;

            if (cbTacDong.Checked == true)
                ttvc.TacDongKhiHau = 1;
            else
                ttvc.TacDongKhiHau = 0;


            ttvc.DiaChiGoiNeuSuCo = txtDiaChiTrahangve.Text;
            ttvc.TenNeuSuCo = txtTenLienLacSuCo.Text;
            ttvc.Id_User = lay_IDUser();
            //context.ThongTinVanChuyens.InsertOnSubmit(ttvc);
            context.SubmitChanges();
            int maVanChuyen = ttvc.Id_TTVC;
            return maVanChuyen;
        }
        private int updateNoiDen(int idNoiDen)
        {
            // insert Noiden
            NoiDen nd = context.NoiDens.Single(i => i.Id_NoiDen == idNoiDen);
            nd.Email = txtEmail.Text;
            nd.Dienthoai = txtDienThoai.Text;
            nd.Diachi1 = txtDiaChi1.Text;
            nd.Diachi2 = txtDiaChi2.Text;
            int maquocgia = int.Parse(ddlQuocGia.SelectedValue.ToString());
            nd.Id_Quocgia = maquocgia;

            nd.Mabuudien = int.Parse(txtMaBuuDien.Text);
            nd.Nguoinhan = txtTen.Text;
            nd.Thanhpho = txtThanhPho.Text;
            if (cbNhaRieng.Checked)
                nd.Nharieng = 1;
            else
                nd.Nharieng = 0;

            nd.IdUser = lay_IDUser();
            //context.NoiDens.InsertOnSubmit(nd);
            context.SubmitChanges();
            int maNoiDen = nd.Id_NoiDen;
            return maNoiDen;
        }

        private int updateLoHang(int idLoHang)
        {
            // update bảng Lô hàng
            LoHang lh = context.LoHangs.Single(i => i.Id_LoHang == idLoHang);
            MatHang matHang = null;
            int banDau = (int)lh.Giong_nhau;
            if (ddlgiongnhau.SelectedValue.ToString() == "1")
            {
                if (banDau != 0)
                {
                    matHang = context.MatHangs.Single(i => i.Id_LoHang == idLoHang);

                    matHang.TenMatHang = txtTenMatHang.Text;
                    matHang.TrongLuong = double.Parse(txtTrongLuong1Goi.Text);
                }
                else 
                {
                    int record = context.MatHangs.Count(i => i.Id_LoHang == idLoHang);
                    if (record <= 0)
                    {
                        matHang = new MatHang();
                        matHang.TenMatHang = txtTenMatHang.Text;
                        matHang.TrongLuong = double.Parse(txtTrongLuong1Goi.Text);
                    }
                }
                lh.Giong_nhau = 1;
                
            }
            else
                lh.Giong_nhau = 0;

            lh.Ten_lo_hang = txtTenLoHang.Text;
            lh.So_goi = int.Parse(ddlsogoi.SelectedValue.ToString());
            lh.Gia_tri = int.Parse(txtGiaTriUocLuong.Text);
            lh.TongTrong_luong = double.Parse(txtTongKhoiLuong.Text);
            //context.LoHangs.InsertOnSubmit(lh);
            context.SubmitChanges();
            int id_lohang = lh.Id_LoHang;
            if (ddlgiongnhau.SelectedValue.ToString() == "1")
            {
                if (banDau != 0)
                {
                    matHang.Id_LoHang = idLoHang;
                    //context.MatHangs.InsertOnSubmit(matHang);
                    context.SubmitChanges();
                }
                else 
                {
                    matHang.Id_LoHang = idLoHang;
                    context.MatHangs.InsertOnSubmit(matHang);
                    context.SubmitChanges();
                    txtTenMatHang.Enabled = true;
                    txtTrongLuong1Goi.Enabled = true;
                }
            }
            return id_lohang;
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            int a = 0;
        }
    }
}